<?php
/**
 * Created by PhpStorm.
 * User: Digvijay
 * Date: 8/29/14
 * Time: 1:38 PM
 */

class Client extends MY_Home {
    public function login() {
        $cartDetails = $this->getCartDetails();
        $clientName = $this->isClientLoggedIn();
        $categories = $this->findAll("Category");
        $terms = $this->findContentByType(Contents::CONTENT_TERMS_AND_CONDITION);
        foreach ($categories as $category) {
            if ($category->getParent() == null) {
                $noOfSub = 0;
                foreach ($categories as $sub) {
                    if ($sub->getParent() != null && $sub->getParent()->getId() == $category->getId()) {
                        $noOfSub++;
                    }
                }
                $category->setNoOfSub($noOfSub);
            }
        }
        $data = array("cart" => $cartDetails, "user" => $clientName, "categories" => $categories, "terms" => $terms);
        $this->load->view('login', $data);
    }

    public function forgotPassword(){
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $username = trim($this->input->post("email"));
            $agency = $this->findAgencyByEmail($username);
            if ($agency != null) {
                $agency = $agency[0];
                $message = " Hello ".$agency->getFirstName() . ", <br/>";
                $message .= "<br/> Your password for www.anmolcards.net is : ". $agency->getPassword();
                $message .= "<br/><br/><br/> Thank You <br/> Anmol Cards ";
                $this->sendMail($username,"Password for Anmolcards.net", $message);
            } else {
                throw new RuntimeException("Invalid Email. Please enter valid email.");
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    public function signin() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $username = trim($this->input->post("username"));
            $password = trim($this->input->post("password"));

            $agency = $this->findAgencyByEmail($username);
            if ($agency != null && $agency[0]->getPassword() == $password && $agency[0]->isActive()) {
                $sessionData = array("agentId" => $agency[0]->getId(), "type" => "CLIENT");
                $this->session->set_userdata('logged_in', $sessionData);
                $response->setData($agency[0]->getFirstName());
            } else {
                throw new RuntimeException("Invalid Email/Passowrd.");
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    public function register() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $businessName = trim($this->input->post("business-name"));
            $firstName = trim($this->input->post("first-name"));
            $lastName = trim($this->input->post("last-name"));
            $email = trim($this->input->post("email"));
            $phone = trim($this->input->post("phone"));
            $password = trim($this->input->post("r-password"));
            $repassword = trim($this->input->post("re-password"));

            if ($password == $repassword) {
                $agency = new Agency();
                $result = $this->findAgencyByEmail($email);
                if ($result != null) {
                    $agency = $result[0];
                    if ($agency->getClientType() == Agency::CLIENT_AGENT) {
                        throw new RuntimeException("Account already exist.");
                    }
                }
                $agency->setBusinessName($businessName);
                $agency->setFirstName($firstName);
                $agency->setLastName($lastName);
                $agency->setEmail($email);
                $agency->setPhone($phone);
                $agency->setDateCreate(new DateTime());
                $agency->setDiscount(0);
                $agency->setClientType(Agency::CLIENT_AGENT);
                //TODO : Encrypt password.
                $agency->setPassword($password);
                $agency->setStatus($agency::STATUS_PENDING);
                $this->save($agency);

                $message = "New Agent Registration Request  <br/>";
                $message .= "Business Name : " . $businessName . "<br/>";
                $message .= "Name :" . $firstName . " " . $lastName . "<br/>";
                $message .= "Pending for your approval.";

                $this->sendMail(MY_Home::$notification->getAgentRegistrationEmail(), "New Agent Registration Request", $message);
                $response->setData("Thank you for Registration. Your account will be activated in some time, will notify you by email.<br> Thank you. Happy Shopping :)");
            } else {
                throw new RuntimeException("Passwords do not match");
            }

        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
} 